package com.honghea.rxhttp.download.file;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import com.honghea.rxhttp.download.bean.DownloadInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;

public class FileUtil {

    public static void writeCache(ResponseBody responseBody, File file, DownloadInfo info) throws IOException {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        long allLength;
        if (info.getContentLength() == 0) {
            allLength = responseBody.contentLength();
        } else {
            allLength = info.getContentLength() + responseBody.contentLength();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(file.getAbsoluteFile(), "rwd");
        FileChannel channelOut = randomAccessFile.getChannel();
        MappedByteBuffer mappedByteBuffer = channelOut.map(FileChannel.MapMode.READ_WRITE,
                info.getReadLength() ,allLength - info.getReadLength());
        byte[] buffer = new byte[1024 * 4];
        int len;
        while ((len = responseBody.byteStream().read(buffer)) != -1) {
            mappedByteBuffer.put(buffer, 0, len);
        }
        responseBody.byteStream().close();
        if (channelOut != null) {
            channelOut.close();
        }
        if (randomAccessFile != null) {
            randomAccessFile.close();
        }
    }


    public static void write(ResponseBody responseBody, File file, DownloadInfo info) throws IOException {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        InputStream in = responseBody.byteStream();
        long totalLength = responseBody.contentLength();
        long downLength = 0;
        FileOutputStream fileOutputStream = new FileOutputStream(file);

        try {
            byte[] buffer = new byte[4096];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                downLength += len;
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fileOutputStream.close();
            in.close();
        }
    }

    /**
     * 获取根目录
     * @param context
     * @return
     */
    public static String getFileRootPath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            return (context.getExternalFilesDirs(""))[0].getAbsolutePath(); // /storage/emulated/0/Android/data/xxx/files
        } else {
            return context.getFilesDir().getAbsolutePath(); // /data/data/xxx/files
        }
    }

    public static List<String> getAllFile(String dir_path) {
        File file = new File(dir_path);
        List<String> filePathList = new ArrayList<>();
        if (!file.mkdirs()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        filePathList.addAll(getAllFile(f.getAbsolutePath()));
                    }
                    if (isPicturePath(f.getPath())) {
                        filePathList.add(f.getAbsolutePath());
                    }
                }
            }
        }
        return filePathList;
    }


    public static boolean isPicturePath(String path) {
        String fileEnd = path.substring(path.lastIndexOf(".") + 1, path.length()).toLowerCase();
        return fileEnd.equals("jpg") || fileEnd.equals("png") || fileEnd.equals("gif") || fileEnd.equals("jpeg") || fileEnd.equals("bmp");
    }

    public static boolean getIsExistImageOfFolder(String dirPath) {
        if(TextUtils.isEmpty(dirPath)){
            return false;
        }
        File file = new File(dirPath);
        if (!file.mkdirs()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        if(getIsExistImageOfFolder(f.getAbsolutePath())){
                            return true;
                        }
                    }
                    if (FileUtil.isPicturePath(f.getPath())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
